package com.mk.springbootvuedemo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mk.springbootvuedemo.config.Result;
import com.mk.springbootvuedemo.entity.News;
import com.mk.springbootvuedemo.entity.User;
import com.mk.springbootvuedemo.mapper.NewsMapper;
import com.mk.springbootvuedemo.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

//定义返回JSON对象的controller
@RestController
//接口统一的路由
@RequestMapping("/news")
public class NewsController {
    @Resource
    NewsMapper newsMapper;

//    定义post接口,post是新增
    @PostMapping("/insert")
    //    @RequestBody把JOSN对象转换成JAVA对象
    public Result<?> save(@RequestBody News news) {
//        应该写一个service类，在controller引入service,setvice引入mapper
        news.setTime(new Date());
        newsMapper.insert(news);
        return Result.success();
    }
    //Delete是删除
    @DeleteMapping("/{id}")//占位符的方式要通过@PathhVariable获取
    public Result<?> update(@PathVariable Long id){
        newsMapper.deleteById(id);
        return Result.success();
    }
    //Put是更新
    @PutMapping("/update")
    public Result<?> update(@RequestBody News news){
        newsMapper.updateById(news);
        return Result.success();
    }
    //Get是查询
    @GetMapping("/search")
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<News> wrapper=Wrappers.<News>lambdaQuery();
//        避免nickName没有数据时查不出来
        if(StrUtil.isNotBlank(search)){
            wrapper.like(News::getTitle,search);
        }
        Page<News> newsPage= newsMapper.selectPage(new Page<>(pageNum,pageSize),wrapper);
        return Result.success(newsPage);
    }
}
